package cn.edu.gduf.luowowo.comment.service.impl;

import cn.edu.gduf.luowowo.comment.domain.TravelComment;
import cn.edu.gduf.luowowo.comment.repository.TravelCommentRepository;
import cn.edu.gduf.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private TravelCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public String saveOrUpdate(TravelComment comment) {
        //如果是一级评论，二级评论
        if (!StringUtils.hasLength(comment.getId())) {
            if (comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE){
                comment.setRefComment(this.get(comment.getRefComment().getId()));
            }
            //添加
            comment.setCreateTime(new Date());
            repository.save(comment);
        }
        return comment.getId();
    }

    @Override
    public TravelComment get(String id) {
        return repository.findById(id).get();
    }

    @Override
    public List<TravelComment> queryByDetailId(Long travelId) {
        //TODO:别人都是传qo的，不知道我会不会翻车
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));
        return template.find(query, TravelComment.class);
    }

    @Override
    public int getCount(Long travelId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));
        return template.find(query, TravelComment.class).size();
    }

    @Override
    public List<TravelComment> queryByCreateTime(int num) {
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"createTime"));
        query.skip(0).limit(num);
        return template.find(query,TravelComment.class);
    }

    @Override
    public List<TravelComment> queryByAuthorId(Long id) {
        List<TravelComment> comments = repository.findByUserId(id);
        return comments;
    }


}
